/***************************************************************
*  NAME:    dh
*	  
*  SYNOPSIS:  diffie-Hellman key exchange
*    	    
*  DESCRIPTION:
*     	    
*  HISTORY:
*      	         pascal - Jan 23, 2012:  Created.
*
***************************************************************/

/*
 *  RSA: if the private key is compromised, any further communication
 *  secured with the key is now exposed.
 *  DH: 'perfect forward secrecy'
 *
 *  g and p are agreed as part of the key exchange. They dont need
 *  to be kept secret.
 *  The server chooses a at random, the client chooses b.
 *
 *  The server computes:
 *  Ys = ( g ^ a) % p
 *
 *  The client computes:
 *  Yc = (g ^ b) % p
 *
 *  The server transmits Ys to the client, the client transmits Yc to the
 *  server.
 *
 *  They comput the final value :  Z = g ^ (a b ) % p
 *
 *   Client:
 *   Z =  Ys ^ b % p  = (g ^ a % p) ^ b % p = g ^(ab) % p
 *
 *   Server :
 *   Z = Yc ^ a % p = (g ^ b % p) ^ a % p  = g ^(ab) % p
 *
 *
 *   DH relies on :
 *
 *    g^ab %p =  g^ba %p = (g^a %)^b %p = (g^b %p)^a %p
 *
 *  Z is the key that is used on both sides as the symetric key.
 *
 *  Discrete logarithm problem:
 *
 *  solve m^x % n = c for m.
 */


void dh_agree(mpz_t p, mpz_t g, mpz_t e, mpz_t Y)
{
	// Y = g^e % p
	mod_pow(Y,g,e,p);
}


void dh_finalize(mpz_t p, mpz_t Y, mpz_t e, mpz_t Z)
{
	// Z = Y^e % p
	mod_pow(Z,Y,e,p);
}



/* Modular inversion */

/*
 *
 *  x^-1 . x = 1 mod m
 *
 *  a . b = M mod m
 *  M . a^-1 = b mod m
 *  M . b^-1 = a mod m
 *
 *  5^-1  = 8 mod 13
 *  6^-1  = 11 mod 13
 *
 *  a . b = M mod m
 *  5 . 6 = 4 mod 13
 *
 *  M . a^-1 = b mod 13
 *  4 . 8^-1 = 6 mod 13
 *
 *  M . b^-1 = a mod 13
 *  4 . 11^-1 = 5 mod 13
 *   
 */
